"""
@Author  : 康帅
@Time    : 2021/1/19 16:46
@Function: 列表推导式
"""
import collections

a = [x + y for x in 'abc' for y in 'def']
# 同等于
res = []
for x in 'abc':
    for y in 'def':
        res.append(x + y)
print(res)

"""filter"""
# 对于可迭代对象中能够传入函数返回True的各项，filter会返回他们(Python中的True包括非空对象
# 而且bool函数调用返回一个对象的真值)
b = filter(bool, ['spam', '', 'ni'])  # <filter object at 0x000001F67DCB7A00>
print(list(b))  # ['spam', 'ni']

# filter可以接受一个可迭代的对象进行处理，并返回一个可迭代对象在python3中产生结果
c = [x for x in ['spam', '', 'ni'] if bool(x)]
print(c)
c = [x for x in ['spam', '', 'ni'] if x]
print(c)

"""多遍迭代器vs单遍迭代器"""
# range支持len和索引，range并不是自己的迭代器(手动迭代时，使用iter产生一个迭代器
# 并且range支持在其他结果上的多个迭代器，这些迭代器会记住他们的位置)
# python3中的map，zip，filter不支持在同一结果上的多个活跃迭代器
d = range(10)
print(len(d))
print(d[3])

R = range(3)
# next(R)  # TypeError: 'range' object is not an iterator
I1 = iter(R)
print(next(I1))  # 0
print(next(I1))  # 1
I2 = iter(R)
print(next(I2))  # 0
print(next(I1))  # 2

Z = zip((1, 2, 3), (10, 11, 12))
l1 = iter(Z)
l2 = iter(Z)
print(next(l1))
print(next(l1))
print(next(l2))

M = map(abs, (-1, 0, 1))
l1 = iter(M)
l2 = iter(M)
print(next(l1), next(l1), next(l1))
print(next(l2))  # StopIteration

R = range(3)
l1, l2 = iter(R), iter(R)
print(next(l1), next(l1), next(l1))  # 0 1 2
print(next(l2))  # 0

"""字典视图可迭代对象"""
D = dict(a=1, b=2, c=3)
print(D)
K = D.keys()
print(K)
# print(next(K))  # TypeError: 'dict_keys' object is not an iterator
I = iter(K)
print(next(I))  # a
print(next(I))  # b
print(next(I))  # c

for k in D.keys():
    print(k)  # a b c

data = {'name': 'ks', 'age': 24}
for k, v in data.items():
    print(k, v)


data_dict = {"name": "ks", "age": 24}
collections.defaultdict(dict)
collections.defaultdict(lambda: 1)

print(data_dict.get("name"))
print(f'{data_dict.setdefault("name")}')

# 列表反转reversed,__reversed__,python自带的一个方法，准确说，应该是一个类,返回反向迭代器
data = [1, 2, 3, 4]
print(list(data.__reversed__()))
print(list(reversed(data)))

# 列表反转reverse
data.reverse()
print(data)
